<?php

defined('BASEPATH') or die('No direct script access allowed');

/**
 * 日记控制器
 * @author  Karson
 * @name    statics.php
 * @since   2013-6-2 9:33:40
 */
class Statics_Controller extends Controller {

    private $type = array('expense' => '收支统计', 'asset' => '资产状况', 'report' => '年度报表');

    function _init() {
        check_level();
    }

    function index() {
        $this->expense();
    }

    function expense() {
        $this->load->library("highcharts");
        $this->highcharts->initialize('default');

        $title = $this->input->post("charttitle");
        $begintime = $this->input->post("startdate", "strtotime");
        $endtime = $this->input->post("enddate", "strtotime");

        $begintime = $begintime ? $begintime : get_unixtime('month');
        $endtime = $endtime ? $endtime : get_unixtime('month', 0, 'end');
        $title = $title ? $title : date("Y年m月");

        if (in_array($title, array('今天', '昨天', '前天')) || date('Y-m-d', $begintime) == date('Y-m-d', $endtime)) {
            $format = "%H:00";
            $temporder = 0;
            $temptable = "SELECT '00:00' AS tempfield,{$temporder} AS temporder";
            for ($i = 1; $i < 24; $i++) {
                $temporder++;
                $temptable .= " UNION ALL SELECT '" . sprintf("%02d", $i) . ":00',{$temporder} AS temporder";
            }
        } else if (in_array($title, array('今年', '去年', '年', date("Y年")))) {
            $format = "%m";
            $temporder = 0;
            $temptable = "SELECT '" . date("m", $begintime) . "' AS tempfield,{$temporder} AS temporder";
            for ($i = 2; $i <= 12; $i++) {
                $temporder++;
                $temptable .= " UNION ALL SELECT '" . date(sprintf("%02d", $i), $begintime) . "',{$temporder} AS temporder";
            }
        } else {
            if ($title == '指定日期' && ($endtime - $begintime) > 86400 * 30) {
                $format = "%Y-%m-%d";
                $format_php = "Y-m-d";
            } else {
                $format = "%m-%d";
                $format_php = "m-d";
            }
            $temporder = 0;
            $temptable = "SELECT '" . date("{$format_php}", $begintime) . "' AS tempfield,{$temporder} AS temporder";
            for ($i = $begintime + 86400; $i < $endtime; $i = $i + 86400) {
                $temporder++;
                $temptable .= " UNION ALL SELECT '" . date("{$format_php}", $i) . "',{$temporder} AS temporder";
            }
        }
        $family_list = $this->family->get_family_list();
        $this->view->assign("family_list", $family_list);
        $user_ids = is_array($_POST['user_ids']) ? array_filter($_POST['user_ids']) : array($_POST['user_ids']);
        $user_ids = array_unique(array_filter($user_ids));
        $user_ids = $user_ids ? $user_ids : array($this->auth->user_id);
        $chartarr = $chartcat = array();
        $this->db->safequery = false;
        $count = 0;
        $family_list[$this->auth->user_id] = $this->auth->fields;
        foreach ($user_ids as $m => $n) {
            $chartarr = array();
            if ($this->auth->fields['family_id'] > 0 && !array_key_exists($n, $family_list))
                continue;
            $userfilter = " AND user_id='{$n}'";
            $sqlstr = "SELECT t.tempfield AS date,SUM(amount) AS amounts,COUNT(o.occurtime) AS items FROM ( {$temptable} ) AS t LEFT OUTER JOIN {pre}bill o
                        ON date_format(from_unixtime(o.occurtime),'{$format}') = t.tempfield
                         AND o.occurtime>={$begintime} AND o.occurtime<{$endtime} {$userfilter} AND type='expense'
                          GROUP BY t.tempfield ORDER BY t.temporder ASC";
            $this->db->query($sqlstr);
            while ($row = $this->db->get_array()) {
                if ($m == 0)
                    $this->highcharts->push_categorie($row['date']);
                $row['amounts'] = $row['amounts'] ? $row['amounts'] : 0;
                $chartarr[] = (float) $row['amounts'];
            }
            $count = count($chartarr);
            $this->highcharts->set_serie(array('name' => $family_list[$n]['username'], 'data' => $chartarr));
        }
        if ($count <= 12) {
            $this->highcharts->unset_xAxis('labels');
        } else {
            $this->highcharts->push_xAxis(array('labels' => array('step' => intval($count / 30))));
            if ($count > 100)
                $this->highcharts->push_plotOptions(array('line' => array('marker' => array('enabled' => false), 'lineWidth' => 1)));
        }
        //$this->highcharts->set_axis_ymin(0);

        $this->highcharts->set_title("{$title}支出统计");

        $chartdata = $this->highcharts->render();

        if ($this->form->is_submit('POST')) {
            echo $chartdata;
        } else {
            $data = array(
                'typelist' => $this->type,
                'chartdata' => $chartdata,
            );
            render("statics/expense", $data);
        }
    }

    function asset() {
        $data = array('typelist' => $this->type,);
        $this->db->query("SELECT SUM(balance) AS nums,type FROM {pre}account WHERE user_id='{$this->auth->user_id}' GROUP BY type");
        $asset = array();
        foreach ($this->account->account_type as $k => $v) {
            $asset[$k] = 0;
        }
        while ($row = $this->db->get_array()) {
            $asset[$row['type']] = $row['nums'];
        }

        //资产合计
        $asset['total'] = array_sum($asset) - $asset['credit'];
        $data['show']['asset'] = $asset;
        //债权
        $one = $this->db->one("SELECT SUM(amount) AS amount, SUM(outstanding) AS outstanding FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type='borrow' AND category_id='1'");
        $one['settled'] = $one['amount'] - $one['outstanding'];
        $one['total'] = $one['outstanding'];
        $data['show']['creditor'] = $one;
        //债务
        $one = $this->db->one("SELECT SUM(amount) AS amount, SUM(outstanding) AS outstanding FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type='borrow' AND category_id='2'");
        $one['settled'] = $one['amount'] - $one['outstanding'];
        $asset['credit'] = -$asset['credit'];
        $one['total'] = $one['outstanding'] + $asset['credit'];
        $data['show']['debtor'] = $one;
        //合计

        render("statics/asset", $data);
    }

    function report() {
        $begintime = get_unixtime('year');
        $endtime = get_unixtime('year', 0, 'end');
        $sqlstr = "SELECT type, `category_id`, DATE_FORMAT(FROM_UNIXTIME(occurtime), '%m') AS `month`,sum(amount) AS `total`
FROM ks_bill WHERE user_id='{$this->auth->user_id}' AND type IN ('expense', 'income') AND occurtime>={$begintime} AND occurtime<={$endtime}
GROUP BY `type`,`category_id`,`month` WITH ROLLUP";
        $this->db->query($sqlstr, 're');
        $list = array(
            'income' => array('total' => array('category' => array('name' => '收入总计'))),
            'expense' => array('total' => array('category' => array('name' => '支出总计')))
        );
        while ($row = $this->db->get_array('re')) {
            $category = get_category($row['category_id']);
            if ($row['month'] == '') {
                $month = 'all';
            } else {
                $month = sprintf("%02d", $row['month']);
            }
            if ($row['category_id'] != '') {
                $list[$row['type']][$row['category_id']][$month] = (int) $row['total'];
                $list[$row['type']][$row['category_id']]['category'] = $category;
                $list[$row['type']]['total'][$month] = isset($list[$row['type']]['total'][$month]) ? $list[$row['type']]['total'][$month] : 0;
                $list[$row['type']]['total'][$month] += (int) $row['total'];
            } else {
                $list[$row['type']]['total']['all'] = (int) $row['total'];
            }
        }
        $total_income = $list['income']['total'];
        $total_expense = $list['expense']['total'];
        $total_income['all'] = isset($total_income['all']) ? $total_income['all'] : 0;
        $total_expense['all'] = isset($total_expense['all']) ? $total_expense['all'] : 0;
        unset($list['income']['total']);
        unset($list['expense']['total']);
        $list['income']['total'] = $total_income;
        $list['expense']['total'] = $total_expense;
        $data = array('typelist' => $this->type, 'reportlist' => $list);
        render("statics/report", $data);
    }

}